/*
 * MP3_Beaney - The MP3 Tag Editor is a free ID3-Tag Editor
 * Copyright (C) 2012 Bernhard Teismann, André Seipelt, Steffen Gruschka, Imanuel Rohlfing
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details. 
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */
package model;

import java.io.File;
import javazoom.jlgui.basicplayer.BasicController;
import javazoom.jlgui.basicplayer.BasicPlayer;
import javazoom.jlgui.basicplayer.BasicPlayerException;

/**
 * Implements a small MP3 Player with start and stop function.
 * <p/>
 * @author Steffen Gruschka
 * @author Bernhard Teismann
 * @author André Seipelt
 * @author Imanuel Rohlfing
 * @version 1.0
 */
public class MP3Player {

    private BasicController control;
    private File currentFile;

    /**
     * Constructor. Creates an empty MP3Player object.
     * <p/>
     */
    public MP3Player(){
        control = null;
        currentFile = null;
    }

    /**
     * Creates a new player and starts it.
     * <p/>
     * @param filename filename of the file to be played
     * @throws MP3Exception
     */
    public void play(String filename) throws MP3Exception{
        if (control != null){
            stop();
        }
        BasicPlayer player = new BasicPlayer();
        control = (BasicController) player;

        try{
            currentFile = new File(filename);
            control.open(currentFile);
            control.play();
            control.setPan(0);
            control.setGain(1.0);
        }catch (BasicPlayerException e){
            throw new MP3Exception(MP3Management.PLAYER_CANNOT_PLAY, currentFile);
        }catch (Exception e){
            throw new MP3Exception(MP3Management.PLAYER_CANNOT_OPEN, currentFile);
        }
    }

    /**
     * Stops the player.
     * <p/>
     * @throws MP3Exception
     */
    public void stop() throws MP3Exception{
        try{
            control.stop();
            control = null;
            currentFile = null;
        }catch (BasicPlayerException ex){
            throw new MP3Exception(MP3Management.PLAYER_CANNOT_STOP, currentFile);
        }
    }

    /**
     * Checks if the Player is playing
     * <p/>
     * @return true if the Player is Playing
     */
    public boolean isPlaying(){
        return control != null;
    }
}